<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8">
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Exemple de liste triable par glisser/déposer</title>
        <meta name="author" content="forresst" />
        <script src="../scripts_js/fonctions.js"></script>
        <script type="text/javascript" src="../scripts_js/XMLHttpRequest.js"></script>
        <script src="../scripts_js/jquery-1.10.0.min.js"></script>
        <script src="../scripts_js/jquery.mobile-1.3.0.js"></script>
        <script src="../scripts_js/jquery-ui.js"></script>
        <script src="../scripts_js/jquery.ui.touch-punch.js"></script>
        <script>
            $(function() {
                $("#sortable0").sortable({
                    connectWith: ".connectedSortable",
                    revert: true
                }).disableSelection();


            });




        </script>
    </head>
    <body onload="verification_session2();recupererCategories();
                init();
                recupererPictogrammes(0);">
        <div style="right: 5%;  position: fixed; margin-top: 1%;">
            <label>Categorie: </label>
            <select name="categorie" id="categorie" onchange="categorie();" >
                <option value="0">Tous</option>
            </select> 
        </div>
        <div style="width: 75%; text-align: center; position: fixed; margin-top: 7%; font-size: 250%; " ><p>Placez les pictogrammes que vous souhaitez utiliser:</p></div>
        <div id="aff_pictos" style=" border: 3px red solid ; height: 90%;  right: 0px;  position: fixed; margin-right: 40px; margin-top: 3%;">

            <ul id="sortable0" class="connectedSortable" style="display: inline-block; list-style-type : none ;width: 150px; height: 95%; overflow:auto;">
            </ul>
        </div>
        <script>
            var pic1 = new Array();
            var idAct = extractUrlParams('id');
            var bd = extractUrlParams('bd');
            var lignes = parseInt(extractUrlParams('x'));
            var colonnes = parseInt(extractUrlParams('y'));
            var width = window.innerWidth / (((lignes ) + 2)*2);
            var height = window.innerHeight / (((colonnes) + 1)*2 );

            //Ajout des pictogrammes
            function addPicto(xml) {
                // Ajout des  pictogrames
                var ul = document.getElementById("aff_pictos").getElementsByTagName('ul')[0];
                var tagnom = xml.getElementsByTagName('listeDesPictogrammes');
                var img = tagnom[0].getElementsByTagName('pictogramme');



                for (var i = 0; i < img.length; i++) {

                    var tdli = document.createElement('li');
                    tdli.setAttribute('id', img[i].getElementsByTagName("identifiant")[0].firstChild.nodeValue);
                    var tdNom = tdli.appendChild(document.createElement("img"));
                    tdNom.setAttribute('src', "../imagesPicto/" + img[i].getElementsByTagName('image')[0].firstChild.nodeValue);
                    tdNom.setAttribute('width', (width / 2));
                    tdNom.setAttribute('height', (height / 2));
                    ul.appendChild(tdli);
                }
            }

            //Placement des élémnets dans la page
            function init() {
                //Affichage des bordures
                var html = document.getElementsByTagName('html')[0];
                if (bd === '2') {
                    html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/deux_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");

                }
                else {
                    if (bd === '4') {
                        html.setAttribute('style', "height: 100%; min-height: 100%; background-image: url(../images/quatre_bordures.png); background-position:center; background-repeat:no-repeat; background-size: 100% 100%; -webkit-background-size: 100% 100%; -o-background-size: 100% 100%; -moz-background-size: 100% 100%;");
                    }

                }
                var ul = document.getElementById("aff_pictos").getElementsByTagName('ul')[0];
                var body = document.getElementsByTagName('body')[0];
                ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: 95%; overflow:auto;");
                
                //Boutton pour valider
                var input = document.createElement('input');
                input.setAttribute('id', "input1");
                input.setAttribute('type', "button");
                input.setAttribute('value', "Enregistrer les pictogrammes");
                input.setAttribute('style', "min-width: " + width + "px; height: " + window.innerHeight / 20 + "px;margin-left: " + window.innerWidth / 2.5 + "px;  margin-top: " + window.innerHeight / 1.1 + "px;position: fixed;");
                input.setAttribute('onclick', "enregistrer();");
                body.appendChild(input);



                // Ajout des carrés pour déposer les pictogrames
                var marge = width;
                var marge_top = window.innerHeight/3;
                for (var i = 1; i <= ((lignes*colonnes)/2); i++) {
                        var div = document.createElement('div');
                        div.setAttribute('style', "display: inline-block; margin-left: " + marge + "px; margin-top:  " + marge_top + "px; border: 5px black solid; width: " + width + "px; height: " + height + "px; position: fixed;");
                        var ul = document.createElement('ul');
                        ul.setAttribute('id', i);
                        ul.setAttribute('class', "connectedSortable");
                        ul.setAttribute('style', "display: inline-block; list-style-type : none ;width: " + width + "px; height: " + height + "px; margin: 0px;  padding-left: " + (width / 4) + "px; padding-top: " + (height / 4) + "px; border: 0px");

                        
                        div.appendChild(ul);
                        body.appendChild(div);
                        $(function() {
                            $("#" + ul.id).sortable({
                                connectWith: ".connectedSortable",
                                revert: true,
                                receive: function(event, ui) {
                                    if (ui.item.closest('ul').children().length === 2) {
                                        $(ui.sender).sortable("cancel");
                                    }
                                }

                            }).disableSelection();

                        });
                    if(i!== 4){
                    marge += (width * 2);
                    
                    }
                    else {
                    marge_top += (height * 2);
                    marge = width;
                    }

                    }
            }

            //Récupère le fichier xml contenant les pictogrammes selon la catégorie
            function recupererPictogrammes(c) {
                //suppression des pictogrammes
                var ul = document.getElementById('sortable0');
                while (ul.firstChild) {
                    ul.removeChild(ul.firstChild);
                }

                var xhr = getXMLHttpRequest();

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                        var docXML = xhr.responseText;
                        var listeDesAdultes = stringToXML(docXML);
                        addPicto(listeDesAdultes);
                    }
                };
                if (parseInt(c) === 0) {
                    xhr.open("POST", "../scripts_php/pictogram_recuperer_tous_mysql.php", false);
                    xhr.send(null);
                }
                else {
                    var fd = new FormData();
                    fd.append("categorie", c);

                    xhr.open('POST', "../scripts_php/picto_recuperer_by_cat_mysql.php", false);
                    xhr.send(fd);
                }

            }

            
            //Vérifie si il y a des cases vides puis enregistre les pictogrammes
            function enregistrer() {

                var ul = document.getElementsByTagName('ul');
                for (var i = 1; i < ul.length; i++) {
                    if (ul[i].id !== "sortable0") {
                        var li = ul[i].getElementsByTagName('li');
                        if (typeof(li[0]) !== "undefined") {
                            pic1[i - 1] = li[0].id;
                        }
                        else {
                            alert("La case n°" + (i - nbPicto) + " est vide");
                            return;
                        }

                    }

                }

                //Enregistrement des pictogrammes
                for (var i = 0; i < pic1.length; i++) {
                    //alert(idAct+" " +pic1[i]+" " +(i+1));
                            enregistrer_pictogramme(idAct, pic1[i],(i+1));                    
                }

                document.location.href = "../generateur.html";
            }
            
            //Enregistrer les pictogrammes de l'activité dans Activité_has_Pictogramme
            function enregistrer_pictogramme(idAct, idPict, num) {
                var xhr = getXMLHttpRequest();

                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                    }
                };

                var fd = new FormData();
                fd.append("idAct", idAct);
                fd.append("idPict", idPict);
                fd.append("num", num);
                xhr.open('POST', "../scripts_php/activite_associer_picto_mysql.php", false);
                xhr.send(fd);

            }
            
            //Extraire les paramètres dans l'adrese url
            function extractUrlParams(nom) {
                var t = location.search.substring(1).split('&');
                for (var i = 0; i < t.length; i++) {
                    var x = t[ i ].split('=');
                    if (x[0] === nom) {
                        return x[1];
                    }
                }
                return null;
            }

            //Récupérer le fichier xml contenant les catégories
            function recupererCategories() {

                var xhr = getXMLHttpRequest();
                xhr.onreadystatechange = function() {
                    if (xhr.readyState === 4 && (xhr.status === 200 || xhr.status === 0)) {
                        //alert("[" + xhr.responseText + "]");
                        //callback(xhr.responseText);
                        var docXML = xhr.responseText;
                        var listeDesCategories = stringToXML(docXML);
                        ajouterCategories(listeDesCategories);
                    }
                };

                xhr.open("POST", "../scripts_php/categorie_recuperer_all_mysql.php", false);
                xhr.send(null);
            }
            
            //Ajouter les catégories dans le select
            function ajouterCategories(xml) {
                //
                var select = document.getElementById("categorie");
                var listeDesCats = xml.getElementsByTagName("categorie");

                for (var i = 0; i < listeDesCats.length; i++) {

                    var option = document.createElement("option");
                    option.setAttribute("value", listeDesCats[i].getElementsByTagName("identifiant")[0].childNodes[0].nodeValue);
                    option.appendChild(document.createTextNode(listeDesCats[i].getElementsByTagName("nom")[0].childNodes[0].nodeValue));
                    select.appendChild(option);

                }
            }
            
            //Affichage des catégories
            function categorie() {
                var indexsite = document.getElementById('categorie');
                recupererPictogrammes(indexsite.options[indexsite.selectedIndex].value);
            }
        </script>
    </body>
</html>